<html>
   <body>
   	<link type="text/css" rel="stylesheet" href="/game.css">
   	 <g:if test="${flash.message!=null}">
   	 	<b>${flash.message}</b>
   	 </g:if>
     Welcome 
     <g:if test="${player!=null}">
     	${player.name}
     	<br>You have collected ${score} points this week.
     </g:if>
     <hr>
     <g:if test="${player!=null}">
	     <!-- glink controller="facebook" 
	     		 action="getFriends" 
	     		 params="[sessionId:player.sessionId]">Get Friends</glink>
	     <br -->
	     <g:if test="${ticket!=null}">
	     		<g:if test="${ticket.sessionId!=null}">
	     			In game since ${ticket.joinedSession}, 
	     			<g:link controller="game" 
	 	 			action="game"
	 	 			params="[gameSessionId:ticket.sessionId, clientSessionId:player.sessionId]">Goto game</g:link>
	     		</g:if>
	     		<g:else>
	     			Waiting for opponent... 
	     		</g:else>
	     </g:if>
	 	 <g:else>
	 	 	Have a nice game of KALAHA<br><br>
	 	 	<div id="ticketDiv">
	 	 	<button type="button" onclick="requestTicket()">Find an opponent</button>
	 	 	</div>
	 	 </g:else>    
	 </g:if>
	 <g:else>
   		<g:link controller="facebook" 
   				action="redirecter" 
   				target="_top">Authenticate</g:link>
	</g:else>
	
	<hr>
	<table><tr>
	<td>Leaderboard</td>
	<td><a href="select" onclick="return toggleLeaderBoard('day');">Daily</a></td>
	<td>/</td>
	<td><a href="select" onclick="return toggleLeaderBoard('week');">Weekly</a></td>
	<td>/</td>
	<td><a href="select" onclick="return toggleLeaderBoard('total');">Total</a></td>
	<td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
	<td><a href="select" onclick="return toggleLeaderBoard('hide');"><div id="leaderBoardButton"></div></a></td>
	</tr></table>
	<hr>
	<div id="leaderBoard"></div>
	<br><br><br>
	<a href="select" onclick="return toggleDebug();"><div id="debugButton">Show debug</div></a>
	<font class="debug">
	<div id="debugOutputDiv"></div>
	</font>
	
	<script type="text/javascript" src="/_ah/channel/jsapi"></script>
	<g:javascript>
	
	var showDebug = false;
	var debugInfo = "";
	function toggleDebug() {
		if (showDebug==true) {
			document.getElementById("debugButton").innerHTML="Show debug";
		} else {
			document.getElementById("debugButton").innerHTML="Hide debug";
		}
		showDebug = !showDebug;
		displayDebugInfo(null);
		return false;
	}
	
	function displayDebugInfo(info) {
		if (info!=null) {
			debugInfo = info + "<hr>" + debugInfo;
		}
		if (showDebug==true) {
			document.getElementById("debugOutputDiv").innerHTML=debugInfo;
		} else {
			document.getElementById("debugOutputDiv").innerHTML="";
		}
	}
	
	var leaderBoardPeriod = "day";
	function toggleLeaderBoard(period) 
	{
		if (period == "hide") {
			document.getElementById("leaderBoardButton").innerHTML="";
			document.getElementById("leaderBoard").innerHTML="";
		} else {
			var xmlhttp;
			if (window.XMLHttpRequest)
  			{// code for IE7+, Firefox, Chrome, Opera, Safari
  				xmlhttp=new XMLHttpRequest();
  			}
			else
  			{// code for IE6, IE5
  				xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  			}
  			xmlhttp.onreadystatechange=function()
  			{
  				if (xmlhttp.readyState==1)
    			{
    				document.getElementById("leaderBoard").innerHTML="Fetch leaderboard from server..."
    			}
  				if (xmlhttp.readyState==4 && (xmlhttp.status==200 || xmlhttp.status==0))
    			{
    				var response = eval("(" + xmlhttp.responseText + ")");
    				var scores = response["leaderboard"];
    				var text = "<table><tr><td><b>Rank</b></td><td><b>Score</b></td><td><b>Name</b></td></tr>";
    				var l = scores.length;
    				if (l==0) {
    					text += "<tr><td>-</td><td>-</td><td>-</td></tr>";
    				} else {
						for (var i = 0; i < l; i++){
						    text += "<tr><td>"+(i+1)+"</td><td>"+scores[i].score+"</td><td>"+scores[i].name+"</td></tr>";
    					}
    				}
    				text+="</table><hr>";
    				document.getElementById("leaderBoard").innerHTML=text;
    				document.getElementById("leaderBoardButton").innerHTML="Hide leaderboard";
    				displayDebugInfo("" + xmlhttp.status);
    			} else if (xmlhttp.readyState==4 && xmlhttp.status!=200)
    			{
    				document.getElementById("leaderBoard").innerHTML="Upps, unexpected response from server, code=" + xmlhttp.status
    				displayDebugInfo("" + xmlhttp.status +" "+ xmlhttp.responseText);
    			}
  			}
			xmlhttp.open("GET","/leaderboard/"+period,true);
			xmlhttp.send();
		}
		
		return false;
	}
	
	var ticket = null;
	var started = false;
	function startTicketPingTimer()
	{
		if (!started) {
			setTimeout("ticketPingTimer()",30*1000);
			started = true;
		}
	}
	function ticketPingTimer()
	{
		var xmlhttp;
		if (window.XMLHttpRequest)
  		{// code for IE7+, Firefox, Chrome, Opera, Safari
  			xmlhttp=new XMLHttpRequest();
  		}
		else
  		{// code for IE6, IE5
  			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  		}
  		xmlhttp.onreadystatechange=function()
  		{
  			if (xmlhttp.readyState==4 && xmlhttp.status==200)
    		{
    			displayDebugInfo("" + xmlhttp.status +" "+ xmlhttp.responseText);
    		} else if (xmlhttp.readyState==4 && xmlhttp.status!=0)
    		{
    			displayDebugInfo("" + xmlhttp.status +" "+ xmlhttp.responseText);
    		}
  		}
  		xmlhttp.open("POST",ticket["edit"]+"&clientSessionId=${player.sessionId}",true);
		xmlhttp.send();
		setTimeout("ticketPingTimer()",30*1000);
	}
	
	function requestTicket()
	{
		var xmlhttp;
		if (window.XMLHttpRequest)
  		{// code for IE7+, Firefox, Chrome, Opera, Safari
  			xmlhttp=new XMLHttpRequest();
  		}
		else
  		{// code for IE6, IE5
  			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  		}
  		xmlhttp.onreadystatechange=function()
  		{
  			if (xmlhttp.readyState==1)
    		{
    			document.getElementById("ticketDiv").innerHTML="Send request to server..."
    		}
  			if (xmlhttp.readyState==4 && (xmlhttp.status==201 || xmlhttp.status==0))
    		{
    			displayDebugInfo("" + xmlhttp.status +" "+ xmlhttp.responseText);
    			document.getElementById("ticketDiv").innerHTML="Waiting for opponent...<br><button type='button' onclick='cancelTicket()'>Cancel ticket</button>";
    			ticket = eval("(" + xmlhttp.responseText + ")");
    			startTicketPingTimer();
    		} else if (xmlhttp.readyState==4 && xmlhttp.status!=201)
    		{
    			document.getElementById("ticketDiv").innerHTML="Upps, unexpected response from server, code=" + xmlhttp.status
    			displayDebugInfo("" + xmlhttp.status +" "+ xmlhttp.responseText);
    		}
  		}
		xmlhttp.open("POST","/tickets/?clientSessionId=${player.sessionId}",true);
		xmlhttp.send();
	}
	
	function cancelTicket()
	{
		var xmlhttp;
		if (window.XMLHttpRequest)
  		{// code for IE7+, Firefox, Chrome, Opera, Safari
  			xmlhttp=new XMLHttpRequest();
  		}
		else
  		{// code for IE6, IE5
  			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  		}
  		xmlhttp.onreadystatechange=function()
  		{
  			if (xmlhttp.readyState==1)
    		{
    			document.getElementById("ticketDiv").innerHTML="Send cancel request to server..."
    		}
  			if (xmlhttp.readyState==4 && (xmlhttp.status==200 || xmlhttp.status==0))
    		{
    			displayDebugInfo("" + xmlhttp.status +" "+ xmlhttp.responseText);
    			window.location.reload()
    			ticket = null
    		} else if (xmlhttp.readyState==4 && xmlhttp.status!=200)
    		{
    			document.getElementById("ticketDiv").innerHTML="Upps, unexpected response from server, code=" + xmlhttp.status
    			displayDebugInfo("" + xmlhttp.status +" "+ xmlhttp.responseText);
    		}
  		}
		xmlhttp.open("DELETE",ticket["edit"]+"&clientSessionId=${player.sessionId}",true);
		xmlhttp.send();
	}
	
     openChannel = function() {
<g:if test="${player!=null}">
        var token = '${player.channelToken}';
</g:if>
        var channel = new goog.appengine.Channel(token);
        
        var handler = {
          'onopen': function() {},
          'onmessage': function(m) { 
          		var state = eval("("+m.data+")");
          		window.location = '/game/game?gameSessionId='+state["sessionId"]+'&clientSessionId=${player.sessionId}'; 
          },
          'onerror': function() {},
          'onclose': function() {}
        };
        var socket = channel.open(handler);

      }
      
     initialize = function() {
        openChannel();
      }
      
      setTimeout(initialize, 100);


</g:javascript>
</html>